package com.offcn.order.service.impl;

import com.offcn.common.response.AppResponse;
import com.offcn.common.utils.DateUtils;
import com.offcn.order.enums.OrderStatusEnumes;
import com.offcn.order.mapper.TOrderMapper;
import com.offcn.order.pojo.TOrder;
import com.offcn.order.pojo.TReturn;
import com.offcn.order.service.OrderService;
import com.offcn.order.service.ProjectFeignService;
import com.offcn.order.vo.req.OrderInfoSubmitVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private TOrderMapper orderMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProjectFeignService projectFeignService;

    @Override
    public TOrder saveOrder(OrderInfoSubmitVo orderVo) {
        TOrder order = new TOrder();
        // 通过orderVo中的accessToken 获取用户Id
        String accessToken = orderVo.getAccessToken();
        String memberId = redisTemplate.opsForValue().get(accessToken);
        if(memberId == null){
            throw new RuntimeException("用户没有登录");
        }
        order.setMemberid(Integer.parseInt(memberId));
        // 赋值属性值
        BeanUtils.copyProperties(orderVo,order);
        // 剩余字段
        // 订单编号
        String orderNum = UUID.randomUUID().toString().replace("-", "");
        order.setOrdernum(orderNum);
        // 订单状态
        order.setStatus(OrderStatusEnumes.UNPAY.getCode());
        // 订单创建时间
        order.setCreatedate(DateUtils.getFormatNow());
        // 支付金额
        //    private Integer money;   //进过计算 重点  公式
        AppResponse<TReturn> response = projectFeignService.getReturnById(orderVo.getReturnid());
        TReturn tReturn = response.getData();
        // 回报支持的金额 * 数量 + 运费  （远程调用）
        Integer money = tReturn.getSupportmoney() * order.getRtncount() + tReturn.getFreight();
        order.setMoney(money);
        // 写入到数据库
        orderMapper.insert(order);
        return order;
    }
}
